package org.ww.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.ww.common.utils.PageUtils;
import org.ww.common.utils.Query;
import org.ww.common.utils.redis.RedisCache;
import org.ww.product.dao.CategoryDao;
import org.ww.product.entity.CategoryEntity;
import org.ww.product.service.CategoryBrandRelationService;
import org.ww.product.service.CategoryService;
import org.ww.product.vo.CatelogLevel2Vo;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    private static final String CATELOG_CACHE = "catelog";

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有的分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //组装成父形结构
        List<CategoryEntity> level1Menus = Optional.ofNullable(categoryEntities)
                .orElseGet(ArrayList::new)
                .stream()
                .filter(c -> c.getParentCid() == 0L)
                .map(c -> {
                    c.setChildren(getChildren(c, categoryEntities));
                    return c;
                })
                .sorted(Comparator.comparingInt(c -> c.getSort() == null ? 0 : c.getSort()))
                .collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> ids) {
        //TODO:检查删除的分类是否被其他地方引用
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public Long[] findCatelogPath(Long attrGroupId) {
        List<Long> catelogPath = new ArrayList<>();
        findParentCatelogPath(attrGroupId, catelogPath);
        Collections.reverse(catelogPath);
        return catelogPath.toArray(new Long[]{});
    }

    /**
     * @param category
     * @CacheEvict：失效模式
     * @Caching：组合注解
     */
//    @CacheEvict(value = "catelog",key = "'getCatalogJson'")
//    @Caching(
//         evict = {
//                 @CacheEvict(value = "catelog",key = "'getCatalogJson'"),
//                 @CacheEvict(value = "catelog",key = "'getLevel1Category'")
//         }
//    )
    @CacheEvict(value = "catelog", allEntries = true)   //allEntries=true 删掉catelog分区下的所有key
    @Override
    public void updateDetails(CategoryEntity category) {
        this.updateById(category);

        String name = category.getName();
        if (StringUtils.isNotBlank(name)) {
            categoryBrandRelationService.updateCategoryName(category.getCatId(), category.getName());
        }
    }

    @Override
    public List<CategoryEntity> getByIds(List<Long> catalogIds) {
        LambdaQueryWrapper<CategoryEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.in(CategoryEntity::getCatId, catalogIds);
        return baseMapper.selectList(wrapper);
    }

    //每次缓存的时候必须指定要存放分区的名称，可以有多个名称，每个名称下的分区都会存一份
    //首次进行会先查缓存，缓存没有就会调用下边的方法，将查询到的数据放入缓存一份，下次再进来进行查询时候直接从缓存中拿数据
    @Cacheable(value = {"catelog"}, key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Category() {
        log.info("查询数据库.....");
        LambdaQueryWrapper<CategoryEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CategoryEntity::getParentCid, 0);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<CategoryEntity> getAllCategory() {
        return baseMapper.selectList(null);
    }

    @Cacheable(value = "catelog", key = "#root.methodName")
    @Override
    public Map<String, List<CatelogLevel2Vo>> getCatalogJson() {
        Map<String, List<CatelogLevel2Vo>> map = new HashMap<>();
//            //二次缓存获取/二次判断
        map = redisCache.getCacheObject(CATELOG_CACHE);
        if (map == null) {
            log.info("缓存未命中...查询数据库..." + Thread.currentThread().getName());
            List<CategoryEntity> allCategory = this.getAllCategory();

            //构造分类数据
            map = Optional.ofNullable(allCategory)
                    .orElseGet(ArrayList::new)
                    .stream()
                    .collect(Collectors.toMap(l1 -> l1.getCatId().toString(), l1 -> {
                        //构造该一级分类的所有二级分类
                        List<CatelogLevel2Vo> catelogLevel2Vos = allCategory.stream()
                                .filter(item -> item.getParentCid().equals(l1.getCatId()))
                                .map(item -> {
                                    CatelogLevel2Vo catelogLevel2Vo = new CatelogLevel2Vo();
                                    catelogLevel2Vo.setCatalog1Id(item.getParentCid().toString());
                                    catelogLevel2Vo.setName(item.getName());
                                    catelogLevel2Vo.setId(item.getCatId().toString());

                                    //构造三级分类
                                    List<CatelogLevel2Vo.Catelog3Vo> catelog3Vos = allCategory.stream()
                                            .filter(l3 -> l3.getParentCid().equals(item.getCatId()))
                                            .map(l3 -> {
                                                CatelogLevel2Vo.Catelog3Vo catelog3Vo = new CatelogLevel2Vo.Catelog3Vo();
                                                catelog3Vo.setCatalog2Id(l3.getParentCid().toString());
                                                catelog3Vo.setName(l3.getName());
                                                catelog3Vo.setId(l3.getCatId().toString());
                                                return catelog3Vo;
                                            }).collect(Collectors.toList());
                                    catelogLevel2Vo.setCatalog3List(catelog3Vos);
                                    return catelogLevel2Vo;
                                }).collect(Collectors.toList());

                        return catelogLevel2Vos;
                    }));
        }
//            redisCache.setCacheObject(CATELOG_CACHE,map);
        return map;
    }

    private List<Long> findParentCatelogPath(Long attrGroupId, List<Long> catelogPath) {
        catelogPath.add(attrGroupId);
        CategoryEntity byId = this.getById(attrGroupId);
        if (byId.getParentCid() != 0) {
            findParentCatelogPath(byId.getParentCid(), catelogPath);
        }
        return catelogPath;
    }

    private List<CategoryEntity> getChildren(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {
        //递归封装子类
        List<CategoryEntity> childrenList = Optional.ofNullable(categoryEntities)
                .orElseGet(ArrayList::new)
                .stream()
                .filter(c -> c.getParentCid().equals(categoryEntity.getCatId()))
                .map(c -> {
                    c.setChildren(getChildren(c, categoryEntities));
                    return c;
                })
                .sorted(Comparator.comparingInt(c -> c.getSort() == null ? 0 : c.getSort()))
                .collect(Collectors.toList());
        return childrenList;
    }

}